package com.wlgc.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.wlgc.dao.UserDao;
import com.wlgc.entity.RestBean;
import com.wlgc.entity.User;
import com.wlgc.mapper.AssignmentMapper;
import com.wlgc.service.*;
import com.wlgc.service.impl.CourseServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/data/request")
public class DataController {
    @Resource
    AssignmentMapper mapper;

    @Resource
    AssignmentService assignmentService;

    @Value("${Class_Study_path.main_path}")
    private String originPath;
    @Autowired
    private UserDao userDao;
    @Resource
    CourseServiceImpl courseService;
    @Resource
    StudentService studentService;
    @Resource
    ClassService classService;
    @Resource
    UserService userService;
    @Resource
    FileService fileService;

    String IllegalFiles = ".exe .js .bat .mp3 .mp4";

    String legalFiles = ".png .jpg .bmp .doc .docx .pdf";


    @GetMapping("/index")
    @PreAuthorize("hasAuthority('index')")
    public RestBean info() {
        String username=SecurityContextHolder.getContext().getAuthentication().getName();
        String avatar_path=userService.getAvatar_PathByUsername(username);
        return new RestBean(200,username,avatar_path);
    }

//学生个人获取个人作业完成情况
   @PostMapping("/get-course-condition")
   @PreAuthorize("hasAuthority('index')")
   RestBean getCourseCondition(@RequestParam("refer") String refer,  @RequestParam("courseName") String courseName)
   {
       if(courseName.isEmpty()||refer.isEmpty())
           return new RestBean(500,"请求失败，完成状态为空！");
       refer=assignmentService.translate(refer);
       String cid=courseService.getCid(courseName);

       return assignmentService.get_Course_Condition(Integer.parseInt(refer),Integer.parseInt(cid));
   }


//管理员查询单个学生某个课程完成情况
    @PostMapping("/get-student-course-condition")
    @PreAuthorize("hasAuthority('check-assignment')")
    RestBean getCourseConditionByAdmin(@RequestParam("refer") String refer,  @RequestParam("courseName") String courseName,
                                       @RequestParam("sid") String sid)
    {
        refer=assignmentService.translate(refer);
        String cid=courseService.getCid(courseName);
        return assignmentService.get_Course_Condition(Integer.parseInt(refer),Integer.parseInt(cid),Integer.parseInt(sid));
    }

//管理员获取班级课程作业所有人完成情况
    @PostMapping("/get-class-course-condition")
    @PreAuthorize("hasAuthority('check-assignment')")
    RestBean getClassAssignment(@RequestParam("refer") String refer,@RequestParam("cno")String cno,
                                @RequestParam("courseName") String courseName)
    { refer=assignmentService.translate(refer);
        String cid=courseService.getCid(courseName);


        return assignmentService.getClass_Course_Condition(Integer.parseInt(refer),Integer.parseInt(cno),Integer.parseInt(cid));
    }


    //上传文件

    @PostMapping("/upload")
    @PreAuthorize("hasAuthority('index')")
    public RestBean upload(String aid, String courseName, String assignmentName, MultipartFile file){
        log.info("上传图片");


        String username = SecurityContextHolder.getContext().getAuthentication().getName();
            User user=userService.getUserByUsername(username);


        //获取文件初始名
        String originalName  = file.getOriginalFilename();
        //获取文件后缀
        String suffix = originalName.substring(originalName.lastIndexOf("."));

        log.info("文件格式{}",suffix);
        if(!legalFiles.contains(suffix)){
            return new RestBean(500,"非法文件格式，请上传.png .jpg .bmp .doc .docx .pdf格式文件");
        }

        String detail = mapper.getDetail(Integer.parseInt(aid));
        String name=studentService.getStudentNameByUid(user.getUid().intValue());
        int sid=studentService.getStudentSidByUid(user.getUid().intValue());
        String cno=studentService.getStudentCnoByUid(user.getUid().intValue());
        //生成新的文件名
        String fileName =  sid + "-" + name+ "-" + assignmentName+ "-" + detail  + suffix;
        log.info("{}",fileName);

        String basePath =  originPath;

        //创建课程文件夹
        basePath +=cno + File.separator + courseName + File.separator;
        log.info("课程路径:{}",basePath);
        File dir1 = new File(basePath);
        if(!dir1.exists()){
            dir1.mkdir();
        }

        //创建学生文件夹
        basePath += sid + "-" + name + File.separator;

        File dir2 = new File(basePath);
        if(!dir2.exists()){
            dir2.mkdir();
        }

        try {
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            return new RestBean<>(500,"上传失败");
        }
         mapper.finishAssignment(sid,Integer.parseInt(aid));
        return new RestBean(200,"上传成功");
    }


//查询所有课程
 @PostMapping("/getCourseByStudent")
 @PreAuthorize("hasAuthority('index')")
    RestBean getCourseByStudent()//后面分方向需要改进/*@RequestParam("cno")String cno*/
 {
     return new RestBean<>(200,"",courseService.getCourseByStudent(studentService.getStudentSidByUsername
             (SecurityContextHolder.getContext().getAuthentication().getName())));
 }
 @PostMapping("/getClassCourseAssignment")
    RestBean getClassAssignment(@RequestParam("courseName") String courseName,@RequestParam("cno") String cno)
 {
     if (!courseName.isEmpty())
     return new RestBean<>(200,"",assignmentService.getCourseAllAssignmentByCourseName(courseName,Integer.parseInt(cno)));
     return new RestBean<>(500,"课程名为空！");
 }
 @PostMapping("/getAllCourse")
    RestBean getAllCourse()
 {
     List<String> courses=courseService.getAllCourse();
     if (!courses.isEmpty())
     return new RestBean<>(200,"",courses);
     return new RestBean<>(500,"课程为空");
 }
 @PostMapping("/getCourseByClass")
 RestBean getCourseByClass(@RequestParam("cno")String cno)
 {
     if(!cno.isEmpty())
     {
         List<String> courses =courseService.getCourseByClass(Integer.parseInt(cno));
         if (!courses.isEmpty())
         {
             return new RestBean<>(200,"",courses);
         }
         return new RestBean<>(500,"课程列表为空");
     }
     return new RestBean<>(500,"班级号为空");

 }
 @PostMapping("/getAllClass")
    RestBean getAllClass()
 {
     List<String> classes=classService.getAllCno();
     if(!classes.isEmpty())
     {
         return new RestBean<>(200,"",classes);
     }
     return new RestBean<>(500,"班级列表为空");
 }
 @PostMapping("/getClassByCourse")
 RestBean getClassByCourse(@RequestParam("courseName")String courseName)
 {
     if (!courseName.isEmpty())
     {
                 List<Integer> cnos=classService.getCnoByCourseName(courseName);
                 if(!cnos.isEmpty())
                 {
                     return new RestBean<>(200,"",cnos);
                 }
                 return new RestBean(500,"班级号为空");
 }
     return new RestBean<>(500,"课程号为空");
 }
 @PostMapping("/addAssignment")
    RestBean addAssignment(@RequestParam("cno") String cno,@RequestParam("courseName") String courseName,
 @RequestParam("detail") String detail,@RequestParam("assignmentName") String assignmentName)
 {
         if(assignmentService.addAssignment(courseName,cno,assignmentName,detail))
         {
             return new RestBean<>(200,"添加成功");
         }
         return new RestBean<>(500,"添加失败");
 }
 @PostMapping("/changeAvatar")
    RestBean changeAvatar(MultipartFile file)
 {
   return fileService.changeAvatar(file);
 }
}
